package com.edu.base.rest;

import com.edu.base.common.utils.IdWorker;
import com.edu.base.rest.enums.MessageType;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.mapper.SysNoticeMapper;
import com.ruoyi.system.service.ISysNoticeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 公告 信息操作处理
 *
 * @author ruoyi
 */
@Api(tags = "我的公告接口，公告类型为通知和公告")
@RestController
@RequestMapping("/api/notice")
public class AppNoticeController extends BaseController {
  @Autowired
  private ISysNoticeService noticeService;

  @Autowired
  private SysNoticeMapper sysNoticeMapper;


  @GetMapping(value = "getUserNotice")
  @ApiOperation(value = "获取会员公告信息", response = SysNotice.class)
  //@ApiImplicitParam(name = "notice", value = "会员公告信息", required = true, dataType = "SysNotice")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "memberId", value = "会员ID", required = true)
  })
  public AjaxResult list(String memberId) {
    // 查询
    SysNotice notice = new SysNotice();
    notice.setCreateBy(memberId);
    //TODO查询当前用户的信息
    List<SysNotice> list = sysNoticeMapper.selectNoticeApiList(notice);
    //查询有群发信息
    String massText = "1";
    List<SysNotice> massTextList = sysNoticeMapper.selectNoticeToMassText(memberId, massText);
    if (CollectionUtils.isNotEmpty(massTextList)) {
      //判断群发信息是否已经删除了
      Iterator<SysNotice> item = massTextList.iterator();
      while (item.hasNext()) {
        SysNotice entity = item.next();
        if (StringUtils.isNotBlank(entity.getRemark())) {
          String userIds[] = entity.getRemark().split(",");
          if (Arrays.asList(userIds).contains(notice.getCreateBy())) {
            item.remove();
          }
        }
      }
      if (CollectionUtils.isNotEmpty(massTextList)) list.addAll(massTextList);
    }
    return AjaxResult.success(list);
  }

  /**
   * 新增通知公告
   */
  @PostMapping("/addNotice")
  @ApiOperation("新增会员公告信息")
  //@ApiImplicitParam(name = "sysNotice", value = "新增会员公告信息", required = true, dataType = "SysNotice")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "memberId", value = "会员ID", required = true),
      @ApiImplicitParam(name = "massText", value = "是否群发（0 是 1 否）"),
      @ApiImplicitParam(name = "noticeTitle", value = "公告标题: (\"其他\", \"0\"  \"注册成功\", \"1\"  \"支付成功\", \"2\"  \"分享成功\", \"3\")"),
      @ApiImplicitParam(name = "noticeType", value = "公告类型（1通知 2公告）"),
      @ApiImplicitParam(name = "noticeContent", value = "公告内容"),
      @ApiImplicitParam(name = "status", value = "公告状态（0正常 1关闭）"),
  })
  public AjaxResult addNotice(String memberId, String massText,
                              String noticeTitle, String noticeType,
                              String noticeContent, String status) {
    SysNotice sysNotice = new SysNotice();
    sysNotice.setCreateBy(memberId);
    sysNotice.setMassText(massText);
    sysNotice.setNoticeType(noticeType);
    sysNotice.setNoticeTitle(noticeTitle);
    sysNotice.setNoticeContent(noticeContent);
    sysNotice.setStatus(status);
    sysNotice.setNoticeId(IdWorker.idAutoIncrement());
    if (StringUtils.isBlank(sysNotice.getMassText())) {
      sysNotice.setMassText("1"); // 不是群发
    }
    if (StringUtils.isNotBlank(sysNotice.getNoticeTitle())) {
      if (MessageType.REGION_SUCCESS.getIndex().equals(sysNotice.getNoticeTitle())) {
        sysNotice.setNoticeTitle(MessageType.REGION_SUCCESS.getName());
      }
      if (MessageType.PAY_SUCCESS.getIndex().equals(sysNotice.getNoticeTitle())) {
        sysNotice.setNoticeTitle(MessageType.PAY_SUCCESS.getName());
      }
      if (MessageType.SHARE_SUCCESS.getIndex().equals(sysNotice.getNoticeTitle())) {
        sysNotice.setNoticeTitle(MessageType.SHARE_SUCCESS.getName());
      }
    }
    return toAjax(noticeService.insertNotice(sysNotice));
  }


  /**
   * 删除通知公告
   */
  @PostMapping("/deleteNotice/{noticeIds}")
  @ApiOperation("删除会员公告信息")
  @ApiImplicitParams({
      // @ApiImplicitParam(name = "noticeIds", value = "位置名称"),
      @ApiImplicitParam(name = "noticeIds", value = "ID集合Long[]", required = true, allowMultiple = true, dataType = "String", paramType = "query"),
      @ApiImplicitParam(name = "memberId", value = "会员ID", required = true)
  })
  public AjaxResult remove(Long[] noticeIds, String memberId) {
    //查询有群发信息
    List<SysNotice> massTextList = sysNoticeMapper.selectNoticeToMassText(memberId, "1");
    // TODO 过滤处理做修改
    List<SysNotice> list = massTextList.stream().filter(v -> {
      return Arrays.asList(noticeIds).contains(v.getNoticeId());
    }).collect(Collectors.toList());
    for (SysNotice sysNotice : list) {
      String remark = "";
      if (StringUtils.isNotBlank(sysNotice.getRemark())) {
        remark = sysNotice.getRemark() + "," + memberId;
      } else {
        remark = memberId;
      }
      sysNotice.setRemark(remark);
      sysNotice.setCreateBy(memberId);
      this.sysNoticeMapper.updateNotice(sysNotice);
    }

    Map<Long, String> map = list.stream().collect(Collectors.toMap(SysNotice::getNoticeId, SysNotice::getNoticeTitle, (v1, v2) -> v1));

    List<String> ids = Lists.newArrayList();
    for (Long id : noticeIds) {
      if (map.containsKey(id)) {
        ids.add(String.valueOf(id));
      }
    }
    if (CollectionUtils.isNotEmpty(ids)) {
      sysNoticeMapper.deleteByIds(ids, memberId);
    }
    return AjaxResult.success();
  }
}
